<?php

function download($url, $save_path)
{

$save_path = $save_path ? $save_path : "./";
$file_name = array_pop(explode("/", $url));
$localfile = $save_path . $file_name;

//检查变量
if (!check_url($url)){
        echo ("Error: URL ". $url ." invalid.\n\n");
		return -1;
}
if (file_exists($localfile)){
        echo ("Error: local file ". $localfile ." exists.\n\n");
		unlink($localfile);
		//return -1;
}

//打开远程文件
$fp = fopen($url, "rb");
if (!$fp){
        echo ("Error: Download ". $url ." failed.\n\n");
		return -1;
}

//打开本地文件
$sp = fopen($localfile, "wb");
if (!$sp){
        echo ("Error: Open local file ". $localfile ." failed.\n\n");
		return -1;
}

//下载远程文件
echo "Downloading, please waiting...\n\n";
while (!feof($fp)){
    $tmpfile .= fread($fp, 1024000);
	echo ".";
}

//保存文件到本地
fwrite($sp, $tmpfile);
fclose($fp);
fclose($sp);
echo "Download file ". $file_name ." succeed!\n\n";
return 1;
}

/* 检查URL合法性函数 */
function check_url($url){
        return preg_match("/^(http|ftp)(:\/\/)([a-zA-Z0-9-_]+[\.\/]+[\w\-_\/]+.*)+$/i", $url);    
}

